package com.springsecurity.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springsecurity.comment.R;
import com.springsecurity.constants.MessageConstant;
import com.springsecurity.constants.RedisConstant;
import com.springsecurity.domain.User;
import com.springsecurity.mapper.UserMapper;
import com.springsecurity.service.UserService;
import com.springsecurity.utlis.JwtUtils;
import com.springsecurity.utlis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <h3>Spring-Security</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2024-07-12 09:50:34
 */
@Transactional
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisUtils redisUtils;
    /**
     * 登录
     * @param map
     * @return
     */
    @Override
    public R login(Map<String, Object> map) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(map.get("userName").toString(), map.get("password").toString());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }
        User user = (User)authenticate.getPrincipal();
        user.setPassword(null);
        String userName = user.getUsername();
        String jwt = JwtUtils.createJWT(userName);
        redisUtils.set(RedisConstant.USER_LOGIN +user.getUsername(),user);
        HashMap<String,Object> mapRest=new HashMap<>();
        mapRest.put("token",jwt);
        return R.success(mapRest, MessageConstant.USERNAME_SUCCESS);
    }
}
